
#include "LuaManager.h"

extern "C"
{
	#include <lua.h>
	#include <lualib.h>
	#include <lauxlib.h>
}

namespace Zha
{

LuaManager::LuaManager(std::string scriptPath)
{
	m_scriptPath = scriptPath;
	InitLuaState();
}

LuaManager::~LuaManager()
{

}

int LuaManager::InitLuaState()
{
	m_pLuaState = luaL_newstate();
	luaopen_base(m_pLuaState);
	luaopen_table(m_pLuaState);
	luaL_openlibs(m_pLuaState);
	luaopen_string(m_pLuaState);
	luaopen_math(m_pLuaState);

	int err = luaL_loadfile(m_pLuaState, m_scriptPath.data());
	if (err)
	{
		Error("Load file:%s failed!", m_scriptPath.data());
	}
	
	if (lua_pcall(m_pLuaState, 0, 0, 0))
	{
		Error("Test pcall failed!");
	}
}

/*example:
*CallFunc("func1", "%d, %s", 3, "abcd")
*d: int , l: long , s: char* , S: std::string* , f: double 
*/
int LuaManager::CallFunc(const char* funcName, const std::string fmt, ...)
{
	int paraCount = 0;

	lua_getglobal(m_pLuaState, funcName);

	va_list args;
	va_start(args, fmt);
	for (int i=0; i<fmt.length(); ++i)
	{
		char ch = fmt[i];
		if (ch == '%')
		{
			++paraCount;
			switch(fmt[i+1])
			{
			case 'd':
				lua_pushnumber(m_pLuaState, va_arg(args, int));
				break;
			case 's':
				lua_pushstring(m_pLuaState, va_arg(args, char*));
				break;
			case 'l':
				lua_pushnumber(m_pLuaState, va_arg(args, long));
				break;
			case 'S':
				va_arg(args, std::string*);
				break;
			case 'f':
	            lua_pushnumber(m_pLuaState, va_arg(args, double));
                break;
			default:
				break;
			}
			++i;
		}
	}
	va_end(args);

	if (lua_pcall(m_pLuaState, paraCount, 1, 0))
	{
		Log("Execute function:%s error");
	}

	return 0;
}

lua_State* LuaManager::GetLuaState()
{
	return m_pLuaState;
}

void LuaManager::NewGlobalTable(char *name)
{
	lua_newtable(m_pLuaState);
	lua_setglobal(m_pLuaState, name);
}

short LuaManager::SetIntToGlobalTable(char *tbName, char *key, int value)
{
	lua_getglobal(m_pLuaState, tbName);
	lua_pushstring(m_pLuaState, key);
	lua_pushnumber(m_pLuaState, value);
	lua_settable(m_pLuaState, -3);
	lua_pop(m_pLuaState, 1);
	return 0;
}

short LuaManager::SetStringToGlobalTable(char *tbName, char *key, char *value)
{
	lua_getglobal(m_pLuaState, tbName);
    lua_pushstring(m_pLuaState, key);
    lua_pushstring(m_pLuaState, value);
    lua_settable(m_pLuaState, -3);
	lua_pop(m_pLuaState, 1);
    return 0;
}

}












